#!/bin/bash

# DevOps SmartBot 快速启动脚本
# 用途: 一键启动所有必要服务

set -e

echo "🚀 DevOps SmartBot - Quick Start Script"
echo "========================================"

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 项目根目录
PROJECT_ROOT="/Users/harry./Desktop/devopsSmartBot"
cd "$PROJECT_ROOT"

# Step 1: 启动监控栈
echo -e "\n${YELLOW}[1/5] 启动监控栈 (Prometheus + Alertmanager)...${NC}"
docker-compose up -d prometheus alertmanager node-exporter redis-exporter mongodb-exporter grafana

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 10

# Step 2: 检查监控服务状态
echo -e "\n${YELLOW}[2/5] 检查监控服务状态...${NC}"
if curl -s http://localhost:9090/-/healthy > /dev/null; then
    echo -e "${GREEN}✓ Prometheus 启动成功${NC} - http://localhost:9090"
else
    echo -e "${RED}✗ Prometheus 启动失败${NC}"
fi

if curl -s http://localhost:9093/-/healthy > /dev/null; then
    echo -e "${GREEN}✓ Alertmanager 启动成功${NC} - http://localhost:9093"
else
    echo -e "${RED}✗ Alertmanager 启动失败${NC}"
fi

# Step 3: 启动数据库服务
echo -e "\n${YELLOW}[3/5] 启动数据库服务 (MongoDB + Redis)...${NC}"
docker-compose up -d mongodb redis

# 等待数据库启动
echo "⏳ 等待数据库启动..."
sleep 5

# Step 4: 启动后端服务
echo -e "\n${YELLOW}[4/5] 启动后端服务...${NC}"
cd "$PROJECT_ROOT/backend"

# 检查依赖
if [ ! -d "node_modules" ]; then
    echo "📦 安装后端依赖..."
    npm install
fi

# 启动后端 (后台运行)
echo "🚀 启动 Node.js 后端..."
npm run dev > /tmp/backend.log 2>&1 &
BACKEND_PID=$!
echo $BACKEND_PID > /tmp/backend.pid

# 等待后端启动
sleep 5

if curl -s http://localhost:8000/health > /dev/null; then
    echo -e "${GREEN}✓ 后端服务启动成功${NC} - http://localhost:8000"
    echo "  PID: $BACKEND_PID"
else
    echo -e "${RED}✗ 后端服务启动失败${NC}"
    echo "  查看日志: tail -f /tmp/backend.log"
fi

# Step 5: 启动前端服务
echo -e "\n${YELLOW}[5/5] 启动前端服务...${NC}"
cd "$PROJECT_ROOT/frontend"

# 检查依赖
if [ ! -d "node_modules" ]; then
    echo "📦 安装前端依赖..."
    npm install
fi

# 启动前端 (后台运行)
echo "🚀 启动 Vue 前端..."
npm run dev > /tmp/frontend.log 2>&1 &
FRONTEND_PID=$!
echo $FRONTEND_PID > /tmp/frontend.pid

# 等待前端启动
sleep 5

echo -e "${GREEN}✓ 前端服务启动成功${NC} - http://localhost:3000"
echo "  PID: $FRONTEND_PID"

# 总结
echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}✅ 所有服务启动完成！${NC}"
echo -e "${GREEN}========================================${NC}"

echo -e "\n📊 服务访问地址:"
echo "  ├─ 前端应用:      http://localhost:3000"
echo "  ├─ 后端API:       http://localhost:8000"
echo "  ├─ Prometheus:    http://localhost:9090"
echo "  ├─ Alertmanager:  http://localhost:9093"
echo "  └─ Grafana:       http://localhost:3001 (admin/admin123)"

echo -e "\n🔑 测试账号:"
echo "  ├─ Admin:   admin@devops.com / admin123"
echo "  ├─ DevOps:  devops@devops.com / devops123"
echo "  └─ Viewer:  viewer@devops.com / viewer123"

echo -e "\n📝 日志文件:"
echo "  ├─ 后端日志: tail -f /tmp/backend.log"
echo "  └─ 前端日志: tail -f /tmp/frontend.log"

echo -e "\n🛑 停止所有服务:"
echo "  bash scripts/shutdown.sh"

echo -e "\n${YELLOW}⚡ 提示: 等待 10-15 秒后访问前端，让服务完全启动${NC}\n"
